import os
import re
import requests
import unicodedata
import cv2

import os

def clear_jpg_images(folder_path):
    """
    清除指定文件夹下的所有JPG格式图像
    参数：folder_path - 要清理的目标文件夹路径（字符串）
    返回：被删除的文件数量（整数）
    """
    # 校验输入路径有效性
    if not os.path.exists(folder_path):
        print("指定路径不存在")
        return
        raise FileNotFoundError(f"指定路径不存在: {folder_path}")
    if not os.path.isdir(folder_path):
        print("指定路径不存在")
        return 
        raise NotADirectoryError(f"路径不是目录: {folder_path}")

    deleted_count = 0  # 删除计数器
    
    # 遍历目录下所有文件
    for filename in os.listdir(folder_path):
        file_path = os.path.join(folder_path, filename)
        
        # 跳过子目录（尽管题目说明不存在，但保留防护逻辑）
        if os.path.isdir(file_path):
            continue
            
        # 统一转换为小写判断扩展名
        if filename.lower().endswith(('.jpg', '.jpeg')):
            try:
                os.remove(file_path)
                deleted_count += 1
            except Exception as e:
                print(f"删除失败 {filename}: {str(e)}")
        print(f"已删除: {folder_path}")       
    return deleted_count

def get_video_frame_count(video_path):
    try:
        # 打开视频文件
        cap = cv2.VideoCapture(video_path)
        if not cap.isOpened():
            print("无法打开视频文件")
            return 0
        # 获取视频的总帧数
        frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
        # 释放视频捕获对象
        cap.release()
        return frame_count
    except Exception as e:
        print(f"发生错误: {e}")
        return 0

def increment_counter():
    base_url = "http://192.168.0.186:5000"
    for i in range(1):  # 测试连续调用5次
        response = requests.post(f"{base_url}/increment_count")
        print(f"第{i+1}次调用: 状态码={response.status_code}, 响应={response.json()}")


def safe_filename(filename):
    """
    安全处理文件名（替代werkzeug的secure_filename）
    功能：
    1. 去除特殊字符
    2. 防止路径穿越
    3. 保留文件扩展名
    """
    # 标准化Unicode字符
    # print("-------",filename)
    filename = unicodedata.normalize('NFKD', filename)
    # 移除非ASCII字符
    filename = filename.encode('ascii', 'ignore').decode('ascii')
    # 保留字母、数字、下划线、短横线和点
    filename = re.sub(r'[^\w\-.]', '', filename)
    # 防止路径穿越
    filename = filename.replace('/', '').replace('\\', '')
    # 处理连续的特殊字符
    filename = re.sub(r'[-_.]+', '_', filename)
    # print(filename)
    return filename.strip('_.-')

def upload_images_from_folder(folder_path, camera_name, video_name, endpoint_url, event = "2"):
    """
    完整图片上传功能（不依赖werkzeug）
    
    参数:
        folder_path: 图片目录路径
        camera_name: 摄像头名称
        video_name: 视频名称
        endpoint_url: 接口地址如"http://localhost:5000/save_images"
    
    返回:
        {
            "status": "success/error",
            "message": "描述信息",
            "uploaded_files": [成功上传的文件列表],
            "failed_files": [失败的文件列表]
        }
    """
    # print("folder_path: ",folder_path)
    # 参数校验
    if not all([folder_path, camera_name, video_name, endpoint_url]):
        return {
            "status": "error",
            "message": "缺少必要参数: folder_path, camera_name, video_name, endpoint_url"
        }

    if not os.path.exists(folder_path):
        return {
            "status": "error",
            "message": f"目录不存在: {folder_path}"
        }

    # 收集图片文件
    image_extensions = ('.png', '.jpg', '.jpeg', '.gif', '.bmp', '.webp')
    uploaded_files = []
    failed_files = []
    file_handles = []

    try:
        # 准备文件列表
        files = []
        for filename in os.listdir(folder_path):
            if filename.lower().endswith(image_extensions):
                try:
                    file_path = os.path.join(folder_path, filename)
                    safe_name = safe_filename(filename)
                    safe_name = filename
                    file_handle = open(file_path, 'rb')
                    files.append(('images', (safe_name, file_handle)))
                    file_handles.append(file_handle)
                    uploaded_files.append(filename)
                except Exception as e:
                    failed_files.append({
                        "filename": filename,
                        "error": str(e)
                    })

        if not files:
            return {
                "status": "error",
                "message": "目录中没有有效的图片文件",
                "supported_extensions": image_extensions
            }

        # 准备表单数据
        data = {
            'cameraName': camera_name,
            'videoName': video_name,
            'event': event
        }

        # 发送请求
        response = requests.post(
            endpoint_url,
            files=files,
            data=data,
            timeout=(10, 30)  # 连接超时10秒，读取超时30秒
        )

        # 处理响应
        result = {
            "status": "success" if response.ok else "error",
            "http_status": response.status_code,
            "uploaded_files": uploaded_files,
            "failed_files": failed_files
        }

        try:
            result.update(response.json())
        except ValueError:
            result["message"] = response.text

        return result

    except requests.exceptions.RequestException as e:
        return {
            "status": "error",
            "message": f"网络请求失败: {str(e)}",
            "uploaded_files": uploaded_files,
            "failed_files": failed_files
        }
    except Exception as e:
        return {
            "status": "error",
            "message": f"系统错误: {str(e)}",
            "uploaded_files": uploaded_files,
            "failed_files": failed_files
        }
    finally:
        # 确保所有文件句柄关闭
        for fh in file_handles:
            try:
                fh.close()
            except:
                pass
# # 使用示例
# if __name__ == "__main__":
#     result = upload_images_from_folder(
#     folder_path="/data/processvideo/chunk_0000/chunk_0000_mp4/problem_cross",
#     camera_name="chunk_0000",
#     video_name="chunk_0000",
#     endpoint_url="http://localhost:5000/save_images"
#     )

#     print(result)


# # 使用示例
# if __name__ == "__main__":
#     target_folder = "/data/processvideo/results/video"
#     try:
#         count = clear_jpg_images(target_folder)
#         print(f"成功删除 {count} 个JPG文件")
#     except Exception as e:
#         print(f"操作失败: {str(e)}")

# clear_jpg_images("/data/control_communication/keyuan/keyuan/problem_cross")